package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.example.demo.dao.BookMapper;
import com.example.demo.dao.ChapterMapper;
import com.example.demo.model.Book;
import com.example.demo.model.Chapter;
import com.example.demo.model.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 功能描述：
 *
 * @Author: Zhanghf
 * @Date: 2021/5/21 10:42
 */
@Controller
public class InfoController {
    @Autowired(required = false)
  //  private ChaptersService chaptersService;
    private ChapterMapper chapterMapper;
    @Autowired(required = false)
private BookMapper bookMapper;
    @GetMapping("info")
    public String index(HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) throws IOException {
        User user = (User) session.getAttribute("user");
        Integer bookid = Integer.parseInt(request.getParameter("bookid"));
        Book book = bookMapper.selectOne(new QueryWrapper<Book>().eq("id", bookid));
        List<Chapter> chapterList = chapterMapper.selectList(new QueryWrapper<Chapter>().eq("bookid", bookid));
        List<Chapter> latestList = chapterList.subList(chapterList.size() - 3, chapterList.size());
        String imgsrc;
        if (book.getPic()==null||book.getPic()!=1) {
            imgsrc = "nopic.gif";
        } else {
            imgsrc = bookid + ".jpg";
        }
        model.addAttribute("user",user);
        model.addAttribute("bookid", bookid);
        model.addAttribute("imgsrc", imgsrc);
        model.addAttribute("latestList", latestList);
        model.addAttribute("chaptersList", chapterList);
        model.addAttribute("book",book);
//        点击量+1
        bookMapper.update(null,new UpdateWrapper<Book>().set("hits",
                bookMapper.selectById(bookid).getCollections()+1
        ));
        return "info";

    }
}
